<?php

namespace App\Models;

use Illuminate\Support\Collection;

class RedpacketTemplate extends Model
{
    protected $table = 'yf_redpacket_template';
    protected $primaryKey = 'redpacket_t_id';
    public $timestamps = false;
    protected $guarded = ['redpacket_t_id'];

    /**
     * 首页版块中补齐红包信息
     */
    public static function getOpenForumRedpacket(array $ids, int $size) : Collection
    {
        return self::select('redpacket_t_id', 'redpacket_t_title', 'redpacket_t_start_date', 'redpacket_t_end_date', 'redpacket_t_orderlimit',
                'redpacket_t_total', 'redpacket_t_giveout', 'redpacket_t_used', 'redpacket_t_price', 'redpacket_t_img')
            ->addSelect(\DB::raw('CONCAT(IF(redpacket_t_total>0, ROUND(redpacket_t_giveout*100/redpacket_t_total), 0), "%") as redpacket_t_usedper'))
            ->where([
                ['redpacket_t_end_date', '>', now()->toDateTimeString()],
                ['redpacket_t_state', '=', 1]
            ])
            ->when($ids, function ($query) use ($ids) {
                return $query->whereNotIn('redpacket_t_id', $ids);
            })
            ->latest('redpacket_t_id')
            ->limit($size)
            ->get();
    }

    public static function getEnableRedpackets() : Collection
    {
        $now = now()->toDateTimeString();
        return self::where([
                ['redpacket_t_state', '=', 1],
                ['redpacket_t_start_date', '<=', $now],
                ['redpacket_t_end_date', '>=', $now]
            ])
            ->get();
    }
}
